﻿<%@ WebHandler Language="C#" Class="service" %>

using System;
using System.Web;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
using System.IO;
using System.Data;

public class service : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/json";
        string act = HttpContext.Current.Request.Params["act"];
        string opt = HttpContext.Current.Request.Params["opt"];
        string business_id = HttpContext.Current.Request.Params["business_id"];
        string data_batch = HttpContext.Current.Request.Params["data_batch"];
        string ids = HttpContext.Current.Request.Params["ids[]"];
        string data_optio = HttpContext.Current.Request.Params["data_optio"];

        if (opt == "download")
        {
            context.Response.Write("{\"code\": 1, \"url\": \"/search/service.ashx?opt=zip&ids[]=" + ids + "&data_batch=" + data_batch + "&data_optio=" + data_optio + "\"}"); 
        }
         if (opt == "print")
        {
            context.Response.Write("{\"code\":1,\"msg\":\"\u6253\u5370\u6587\u6863\u83b7\u53d6\u6210\u529f\",\"url\":[" + print(ids, data_optio) + "],\"info\":\"" + data_optio + "\"}");
        }
         if (opt == "zip")
         {
             download(ids, data_optio);
         }
    }
    MsSqlHelper mssql = new MsSqlHelper();
    Common init = new Common();
    public string typename = "";

    /// <summary>
    /// 预览JSON组装
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    public string print(string ids,string data_optio)
    {
        string[] sArray = ids.Split(',');
        string url = "";
        string sql = "";
        foreach (string i in sArray)
        {
            /*
            if (data_optio == "iquanbu")
            {
                sql  = "select rtrim(url) url from spls_ck a(nolock),[ImageDoc] b(nolock) where a.spid=b.detailid and a.pihao=b.fzxx1 and b.type_id in('fa','sh','ghssh','ghsfa','rk') and a.plh ='" + i.ToString() + "'";
                if (data_optio == "fa" || data_optio == "sh" || data_optio == "ghssh" || data_optio == "ghsfa" || data_optio == "kr" || data_optio == "quanbu")
                {
                sql += " union all ";
                sql += "select rtrim(url) url from spls_ck a(nolock),[ImageDoc] b(nolock) where a.spid=b.detailid and b.type_id in('fa','sh','ghssh','ghsfa','rk') and a.plh ='" + i.ToString() + "'";
               }
                sql +=  " union all ";
                sql +=  "select rtrim(url) url from spls_ck a(nolock),[ImageDoc] b(nolock) where left(a.pici,14)=b.detailid and a.spid=b.fzxx1 and b.type_id in('fa','sh','ghssh','ghsfa','rk') and a.plh ='" + i.ToString() + "'";
                sql += " union all ";
                sql += "select rtrim(url) url from spls_ck a(nolock),[ImageDoc] b(nolock) where left(a.pici,14)=b.detailid and b.type_id in('fa','sh','ghssh','ghsfa','rk') and a.plh ='" + i.ToString() + "'";
            }
            else
            {
                sql = "select rtrim(url) url from spls_ck a(nolock),[ImageDoc] b(nolock) where a.spid=b.detailid and a.pihao=b.fzxx1 and b.type_id='" + data_optio + "' and a.plh ='" + i.ToString() + "'";
                if (data_optio == "fa" || data_optio == "sh" || data_optio == "ghssh" || data_optio == "ghsfa" || data_optio == "kr" || data_optio == "pj")
                {
                    sql += " union all ";
                    sql += " select rtrim(url) url from spls_ck a(nolock),[ImageDoc] b(nolock) where a.spid=b.detailid and b.type_id='" + data_optio + "' and a.plh ='" + i.ToString() + "'";
                }
                sql += " union all ";
                sql +=  "select rtrim(url) url from spls_ck a(nolock),[ImageDoc] b(nolock) where left(a.pici,14)=b.detailid and a.spid=b.fzxx1 and b.type_id='" + data_optio + "' and a.plh ='" + i.ToString() + "'";
                sql += " union all ";
                sql += "select rtrim(url) url from spls_ck a(nolock),[ImageDoc] b(nolock) where left(a.pici,14)=b.detailid and b.type_id='" + data_optio + "' and a.plh ='" + i.ToString() + "'";
            }
             */
            if (data_optio == "iquanbu" || data_optio == "quanbu")
            {
                if (data_optio == "iquanbu")
                {
                    sql += "select rtrim(url) url from spls_ck a(nolock),[ImageDoc] b(nolock) where left(a.pici,14)=b.detailid and a.spid=b.fzxx1 and b.type_id in('fa','sh','ghssh','ghsfa','rk') and a.plh ='" + i.ToString() + "' group by url";
                    sql += " union all ";
                    sql += "select rtrim(url) url from spls_ck a(nolock),[ImageDoc] b(nolock) where left(a.pici,14)=b.detailid and b.type_id in('fa','sh','ghssh','ghsfa','rk') and a.plh ='" + i.ToString() + "' group by url";
                }
                if (data_optio == "quanbu")
                {
                    sql += "select rtrim(url) url from spls_ck a(nolock),[ImageDoc] b(nolock) where a.spid=b.detailid and a.spid=b.fzxx1 and b.type_id in('zc','pj','bz','sm','rf','pf','sf') and a.plh ='" + i.ToString() + "' group by url";
                    sql += " union all ";
                    sql += "select rtrim(url) url from spls_ck a(nolock),[ImageDoc] b(nolock) where a.spid=b.detailid and b.type_id in('zc','pj','bz','sm','rf','pf','sf') and a.plh ='" + i.ToString() + "' group by url";
                }
            }
            else
            {
                if (data_optio == "bg")
                {
                    sql = "select rtrim(url) url from spls_ck a(nolock),[ImageDoc] b(nolock) where a.spid=b.detailid and a.pihao=b.fzxx1 and b.type_id='" + data_optio + "' and a.plh ='" + i.ToString() + "' group by url";
                }
                if(data_optio=="pj"||data_optio=="zc"||data_optio=="pj"||data_optio=="bz"||data_optio=="sm"||data_optio=="rf"||data_optio=="pf"||data_optio=="sf")
                {
                    sql = "select rtrim(url) url from spls_ck a(nolock),[ImageDoc] b(nolock) where a.spid=b.detailid and b.type_id='" + data_optio + "' and a.plh ='" + i.ToString() + "' group by url";
                }
                if (data_optio == "fa" || data_optio == "sh" || data_optio == "ghssh" || data_optio == "ghsfa" || data_optio == "rk")
                {
                    sql += "select rtrim(url) url from spls_ck a(nolock),[ImageDoc] b(nolock) where left(a.pici,14)=b.detailid and a.spid=b.fzxx1 and b.type_id='" + data_optio + "' and a.plh ='" + i.ToString() + "' group by url";
                    sql += " union all ";
                    sql += "select rtrim(url) url from spls_ck a(nolock),[ImageDoc] b(nolock) where left(a.pici,14)=b.detailid and b.type_id='" + data_optio + "' and a.plh ='" + i.ToString() + "' group by url";
                }
            }
            
            
            
            
            //url += sql;
            DataTable dt = mssql.ExecuteDt(sql);
            for (int n = 0; n < dt.Rows.Count; n++)
            {
               // url += "\"" + dt.Rows[n]["url"].ToString() + "\",";

                url += "\"" + init.imagefileurl(dt.Rows[n]["url"].ToString()) + "\",";
            }
        }
        //string sql = "select rtrim(url) url from spls_ck a(nolock),[ImageDoc] b(nolock) where a.spid=b.detailid and a.pihao=b.fzxx1 and a.plh in(" + ids + ")";

        //HttpContext.Current.Response.Write(url);
        if (url.IndexOf(",") > 0)
        {
            url = url.Remove(url.Length - 1, 1);
        }
        return url;
    }
    /// <summary>
    ///下载 组装
    /// </summary>
    /// <param name="ids"></param>
    public void download(string ids,string optio)
    {
        ZipFileByCode(ids,optio);
    }

    /// <summary>
    /// 压缩打包文件
    /// </summary>
    /// <param name="ids">ids格式：url\新名字,url\新名字,...</param>
    public void ZipFileByCode(string ids,string optio)
    {
        string sql = "";
        string test = "";
        try
        {            
            string content = "图片资料打包\r\nCopyright © 2018 Sitaier QQ:613329777 All rights reserved";
            if (ids.Length != 0)
            {
                string[] sArray = ids.Split(',');                

                MemoryStream ms = new MemoryStream();
                byte[] buffer = null;

                using (ZipFile file = ZipFile.Create(ms))
                {
                    file.BeginUpdate();
                    file.NameTransform = new MyNameTransfom();//通过这个名称格式化器，可以将里面的文件名进行一些处理。默认情况下，会自动根据文件的路径在zip中创建有关的文件夹。
                    file.SetComment(content);
                    foreach (string i in sArray)
                    {
                        //int index = sArray.ToString().IndexOf(i);
                        DataTable dt = new DataTable();                        
                         sql = "select distinct rtrim(url) url,rtrim(plh) plh,rtrim(c.spmch) as spmch,rtrim(b.extend) as extend,rtrim(type_id) type_id,rtrim(b.leibie) as leibie,rtrim(b.fzxx1) as pihao"
                            + " from spls_ck a(nolock),[ImageDoc] b(nolock),spkfk c(nolock) where a.spid=b.detailid and a.spid=c.spid and a.plh ='" + i.ToString() + "'";  
                        switch (optio)
                        {
                            case "quanbu":
                                sql += " and b.type_id in('zc','pj','bz','sm','rf','pf','sf')";
                                break;
                            case "bg":
                                sql += " and b.type_id='bg' and a.pihao=b.fzxx1";
                                break;
                            case "pj":
                                sql += " and b.type_id='pj'";
                                break;
                            case "cj":
                                sql += " and b.type_id='cj'";
                                break;
                            case "sm":
                                sql += " and b.type_id='sm'";
                                break;
                            case "bz":
                                sql += " and b.type_id='bz'";
                                break;
                            case "sf":
                                sql += " and b.type_id='sf'";
                                break;
                            case "pf":
                                sql += " and b.type_id='pf'";
                                break;
                            case "rf":
                                sql += " and b.type_id='rf'";
                                break;
                            default:
                                sql += " and 1=2";
                                break;                             
                        }
                        dt = mssql.ExecuteDt(sql);
                        
                        if (dt.Rows.Count == 0)
                        {

                            sql = "select distinct rtrim(url) url,rtrim(plh) plh,rtrim(b.detailid) as spmch,rtrim(b.extend) as extend,rtrim(type_id) type_id,rtrim(b.leibie) as leibie,rtrim(a.pihao) as pihao"
                                + " from spls_ck a(nolock),[ImageDoc] b(nolock) where left(rtrim(a.pici),14)=b.detailid  and a.plh ='" + i.ToString() + "'";
                            switch (optio)
                            {
                                case "iquanbu":
                                    sql += " and b.type_id in('fa','sh','ghssh','ghsfa','rk')";
                                    break;
                                case "fa":
                                    sql += " and b.type_id='fa'";
                                    break;
                                case "sh":
                                    sql += " and b.type_id='sh'";
                                    break;
                                case "ghssh":
                                    sql += " and b.type_id='ghssh'";
                                    break;
                                case "ghsfa":
                                    sql += " and b.type_id='ghsfa'";
                                    break;
                                case "rk":
                                    sql += " and b.type_id='rk'";
                                    break;
                                default:
                                    sql += " and 1=2";
                                    break;
                            }
                            dt = mssql.ExecuteDt(sql);
                        } 
                        
                        for (int n = 0; n < dt.Rows.Count; n++)
                        {
                            /*
                            if (File.Exists(HttpContext.Current.Server.MapPath("~") + dt.Rows[n]["url"].ToString()))
                            {
                                file.Add(HttpContext.Current.Server.MapPath("~") + dt.Rows[n]["url"].ToString(), dt.Rows[n]["spmch"].ToString() + "_" + dt.Rows[n]["leibie"].ToString() + "_" + dt.Rows[n]["pihao"].ToString() + "_" + n + "_" + dt.Rows[n]["plh"].ToString() + dt.Rows[n]["extend"].ToString());
                            }                             
                             */
                            if (File.Exists("H:\\" + dt.Rows[n]["url"].ToString()))
                            {
                                file.Add("H:\\" + dt.Rows[n]["url"].ToString(), dt.Rows[n]["spmch"].ToString() + "_" + dt.Rows[n]["leibie"].ToString() + "_" + dt.Rows[n]["pihao"].ToString() + "_" + n + "_" + dt.Rows[n]["plh"].ToString() + dt.Rows[n]["extend"].ToString());
                                
                            }
                        }
                    }

                    file.CommitUpdate();
                    buffer = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(buffer, 0, buffer.Length);
                }
                DateTime dts = DateTime.Now;
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=文档系统" + dts.ToLocalTime().ToString() + ".zip");
                HttpContext.Current.Response.BinaryWrite(buffer);
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
            }
        }
        catch (Exception ex)
        {
            HttpContext.Current.Response.Write("{\"code\":0,\"msg\":\"\u6ca1\u6709\u53ef\u4e0b\u8f7d\u6216\u6253\u5370\u7684\u6587\u6863||" + test + "||" + HttpContext.Current.Server.MapPath("~") + "||" + sql + "||" + ex.ToString() + "\"}");
        }
    }

    public void downloadx(string ids)
    {
        string[] sArray = ids.Split(',');
        string url = "";
        foreach (string i in sArray)
        {
            string sql = "select rtrim(url) url from spls_ck a(nolock),[ImageDoc] b(nolock) where a.spid=b.detailid and a.pihao=b.fzxx1 and a.plh ='" + i.ToString() + "' group by url";
            DataTable dt = mssql.ExecuteDt(sql);
            for (int n = 0; n < dt.Rows.Count; n++)
            {
                url += dt.Rows[n]["url"].ToString() + ",";
            }
        }
        if (url.IndexOf(",") > 0)
        {
            url = url.Remove(url.Length - 1, 1);
        }
        ZipFileByCodex(url);
    }

    /// <summary>
    /// 压缩打包文件
    /// </summary>
    /// <param name="ids"></param>
    public static void ZipFileByCodex(string ids)
    {
        if (ids.Length != 0)
        {
            MemoryStream ms = new MemoryStream();
            byte[] buffer = null;

            using (ZipFile file = ZipFile.Create(ms))
            {
                file.BeginUpdate();
                file.NameTransform = new MyNameTransfom();//通过这个名称格式化器，可以将里面的文件名进行一些处理。默认情况下，会自动根据文件的路径在zip中创建有关的文件夹。

                string[] sArray = ids.Split(',');
                foreach (string i in sArray)
                {
                    // file.Add(HttpContext.Current.Server.MapPath("~")+i.ToString(),);
                    file.Add(HttpContext.Current.Server.MapPath("~") + i.ToString());
                }
                file.CommitUpdate();

                buffer = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(buffer, 0, buffer.Length);
            }
            DateTime dt = DateTime.Now;
            System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=文档系统" + dt.ToLocalTime().ToString() + ".zip");
            System.Web.HttpContext.Current.Response.BinaryWrite(buffer);
            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.End();
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public class MyNameTransfom : ICSharpCode.SharpZipLib.Core.INameTransform
    {

        #region INameTransform 成员

        public string TransformDirectory(string name)
        {
            return null;
        }

        public string TransformFile(string name)
        {
            return Path.GetFileName(name);
        }

        #endregion
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}